import settle from '../core/settle.js';

export default function xhrAdapter(config) {
  // Object.assign(defaultConfig, config);
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    let {method, url, headers, data, timeout, cancelToken, validateStatus} = config;

    if (method === 'get' && data) {
      const search = Object.entries(data)
        .map(([key, value]) => {
          return `${key}=${value}`;
        })
        .join('&');
      url = `${url}?${search}`;
      data = null;
    }
    method = method.toUpperCase();

    config = {method, url, headers, data, timeout, cancelToken, validateStatus};

    xhr.open(method, url, true);

    Object.keys(headers).forEach(key => {
      xhr.setRequestHeader(key, headers[key]);
    });

    xhr.onreadystatechange = function () {
      if (xhr.status === 200 && xhr.readyState === 4) {
        const response = {
          data: xhr.response,
          status: xhr.status,
          statusText: xhr.statusText,
          headers,
          config,
          request: xhr
        };
        // resolve(response);
        settle(resolve, reject, response);
      }
    };

    timeout && (xhr.timeout = timeout);

    // 当请求遇到错误时，将触发error 事件。
    // url: 'https://somewhere.org/i-dont-exist'
    xhr.onerror = function () {
      reject('error');
    };
    xhr.onabort = function () {
      reject('onabort');
    };
    xhr.ontimeout = function () {
      reject('ontimeout');
    };

    if (cancelToken) {
      console.log(cancelToken);
      cancelToken.promise.then(reason => {
        xhr.abort();
        // abort 回调里执行reject，已经拒绝这个Promis了，下面这个reject的作用？
        // reject(reason);
      });
    }

    xhr.send(data);
  });
}
